package com.ucenter.server.user.utils;

import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.system.auth.AuthUtil;
import com.system.auth.model.AuthClient;
import com.system.comm.utils.FrameSpringBeanUtil;
import com.ucenter.server.user.pojo.Website;
import com.ucenter.server.user.service.WebsiteService;

public class WebsiteUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(WebsiteUtil.class);

	public static void init() {
		ThreadPoolTaskExecutor task = FrameSpringBeanUtil.getBean(ThreadPoolTaskExecutor.class);
		task.execute(new Runnable() {
			@Override
			public void run() {
				ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
					@Override
					public Thread newThread(Runnable r) {
						Thread thread = new Thread(r);
						LOGGER.info("初始同步站点密钥的线程:" + thread.getName());
						return thread;
					}
				});
				//线程，每隔30秒调用一次
				Runnable runnable = new Runnable() {
					public void run() {
						//初始website的信息
						WebsiteService websiteService = FrameSpringBeanUtil.getBean(WebsiteService.class);
						List<Website> list = websiteService.findUse();
						for (Website website : list) {
							AuthClient client = new AuthClient(website.getWebsiteId(), website.getName(), website.getDomain(), website.getSecret(), "http://127.0.0.1/callback.htm");
							AuthUtil.addAuthClient(client);
						}
					}
				};
				// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间  
				service.scheduleAtFixedRate(runnable, 10, 30, TimeUnit.SECONDS);
			}
		});
	}
}
